package pratice.jdbc;

import com.alibaba.fastjson.JSON;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import framework.util.generator.FieldForGeneratorMysql;
import org.apache.ibatis.type.JdbcType;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 吴宇亮 on 2019/6/26 21:43
 */
public class springJdbcLearn {

    @Test
    public void test01() throws SQLException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-db.xml");
        ComboPooledDataSource dataSource = (ComboPooledDataSource)applicationContext.getBean("dataSource");
        Connection connection = dataSource.getConnection();

//        查询表中有什么字段
        PreparedStatement preparedStatement = connection.prepareStatement("desc sys_code");
        ResultSet resultSet = preparedStatement.executeQuery();
        List list = convertList(resultSet);
        list.forEach(System.out::println);

        System.out.println(JdbcType.VARCHAR.name().toLowerCase());
        preparedStatement.close();
        connection.close();
    }

    private static List<FieldForGeneratorMysql> convertList(ResultSet resultSet) throws SQLException{
        List<FieldForGeneratorMysql> list = new ArrayList<>();
        ResultSetMetaData row = resultSet.getMetaData();//获取元数据
        int columnCount = row.getColumnCount();//获取列的数量
        while (resultSet.next()) {
            System.out.println();
            Map rowData = new HashMap();//声明Map
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(row.getColumnName(i), resultSet.getObject(i));//获取键名及值
            }
            FieldForGeneratorMysql columnVo = JSON.parseObject(JSON.toJSONString(rowData), FieldForGeneratorMysql.class);
            list.add(columnVo);
        }
        return list;
    }

}
